from django.apps import AppConfig
from django.db import connection
from django.core.management import call_command
from django.conf import settings


class RoleConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'role'

    def ready(self):
        # 在应用启动时检查是否需要初始化系统
        self._init_system_if_needed()

    def _init_system_if_needed(self):
        """
        检查是否需要初始化系统，如果需要则执行初始化
        """
        try:
            # 检查数据库连接是否正常
            with connection.cursor() as cursor:
                # 检查user表是否存在
                cursor.execute(
                    "SELECT COUNT(*) FROM information_schema.tables "
                    "WHERE table_name = 'sys_user'"
                )
                table_exists = cursor.fetchone()[0] > 0
                
                if not table_exists:
                    # 表不存在，可能是首次运行，稍后会通过migrate创建
                    return
                    
                # 检查sys_user表中是否已有用户
                cursor.execute("SELECT COUNT(*) FROM sys_user")
                user_count = cursor.fetchone()[0]
                
                # 如果没有用户，则执行系统初始化
                if user_count == 0:
                    print("检测到系统中无任何用户，正在初始化系统...")
                    call_command('init_system', verbosity=0)
                    print("系统初始化完成！")
        except Exception as e:
            # 忽略检查过程中的异常，避免影响应用启动
            pass